package com.wstuo.itsm.request.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.attachment.dao.IAttachmentDAO;
import com.wstuo.common.config.attachment.entity.Attachment;
import com.wstuo.common.rules.DroolsFacade;
import com.wstuo.common.rules.drool.RulePathFile;
import com.wstuo.common.rules.drool.RulePathType;
import com.wstuo.common.rules.entity.RulePackage;
import com.wstuo.common.tools.dao.IEmailDAO;
import com.wstuo.common.tools.dao.IEventAttachmentDAO;
import com.wstuo.common.tools.dto.EmailMessageDTO;
import com.wstuo.common.tools.entity.EmailMessage;
import com.wstuo.common.tools.entity.EventAttachment;
import com.wstuo.common.tools.service.IEmailService;
import com.wstuo.itsm.request.dto.RequestDTO;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.util.StringUtils;
/**
 * 邮件转请求Service类
 * @author QXY
 */
public class MailToRequestService implements IMailToRequestService {
	//规则
    private DroolsFacade droolsFacade = new DroolsFacade();
    @Autowired
    private IUserDAO userDAO;
	@Autowired
	private IRequestService requestService;
	@Autowired
	private IEmailService emailService;
	@Autowired
	private IEmailDAO emailDAO;
	@Autowired
	private IEventAttachmentDAO eventAttachmentDAO;
	@Autowired
	private IAttachmentDAO attachmentDAO;
	final static Logger LOGGER = Logger.getLogger(MailToRequestService.class);

	/**
	 * 邮件扫描，自动转请求
	 */
	@Transactional
	public void convertMail(){
		//mail message list
	    List<EmailMessageDTO> ems= emailService.receiveMail();
	    //EmailMessageDTO to RequestDTO
	    List<RequestDTO> mails = emailMessageDTO2RequestDTO(ems);
	    //邮件转请求
	    mailToRequest(mails);
	}
	
	/**
	 * EmailMessageDTO to RequestDTO
	 * @param dtos
	 */
	@Transactional
	private List<RequestDTO> emailMessageDTO2RequestDTO(List<EmailMessageDTO> ems){
		LanguageContent lc=LanguageContent.getInstance();
		String actionName = lc.getContent("common.add")+lc.getContent("title.email.mailToRequest");
		List<RequestDTO> mails = new ArrayList<RequestDTO>();
		for(EmailMessageDTO emDTO:ems){
	    	if(StringUtils.hasText(emDTO.getSubject())){
	    		RequestDTO requestDTO=new RequestDTO();
	    		requestDTO.setEtitle(emDTO.getSubject());
	    		requestDTO.setEdesc(emDTO.getContent());
	    		requestDTO.setEmailMessage(emDTO.getEmailMessageId());
	    		requestDTO.setCreatedByEmail(emDTO.getFromUser());
	    		requestDTO.setActionName(actionName);
	    		requestDTO.setAttachmentStr("");
	    		mails.add(requestDTO);
			}
		}
		return mails;
	}
	/**
	 * 需要邮件转请求
	 * @param mails
	 */
	@Transactional
	private void mailToRequest(List<RequestDTO> mails){
		if(mails.size()>0){
			//是否需要转请求匹配规则
		    droolsFacade.matchRules(mails, new String[]{RulePackage.MAILTOREQUEST},RulePathType.RequestMail.getValue(),RulePathFile.URL_SETREQUESTMAILRULESOURCE.getValue());
		    for(RequestDTO requestDTO : mails){
		    	Long eno = 0L;
		    	if(requestDTO.getMailToRequest()){
			    	//根据发送的邮箱匹配请求人
			    	User createUser = null;
			    	if(requestDTO.getCreatedByNo()==null || requestDTO.getCreatedByNo()==0){
			    		List<User> users = userDAO.findUserByEmail(new String[]{requestDTO.getCreatedByEmail()});
				    	if(users.size()>0){
				    		createUser = users.get(0);
				    		requestDTO.setCreatedByNo(createUser.getUserId());
				    	}
			    	}else{
			    		createUser = userDAO.findById(requestDTO.getCreatedByNo());
			    	}
			    	if(requestDTO.getCreatedByNo()==null || requestDTO.getCreatedByNo()==0){
			    		LOGGER.error("mailToRequest: Through rules and email address cannot determine the claimant, mail transfer request failed!");
		        		continue;
			    	}else{
			    		try{
		            		eno = requestService.saveRequest(requestDTO);
		            		//修改邮件标识为已经转请求
			            	if(requestDTO.getEmailMessage()!=null){
			        	    	EmailMessage emailMessage=emailDAO.findById(requestDTO.getEmailMessage());
			        	    	if(emailMessage!=null && emailMessage.getAttachment()!=null){
			                    	//Save EventAttachemnt
			                    	for(Attachment  ac :emailMessage.getAttachment()){
			                    		ac.setType("itsm.request");
			                    		if(createUser!=null)
			                    			ac.setCreator(createUser.getLoginName());
			                    		attachmentDAO.merge(ac);
			                    		EventAttachment attr=new EventAttachment();
			    	            		attr.setEno(eno);
			    	                	attr.setEventType("itsm.request");
			    	                	attr.setAttachment(ac);
			    	                	eventAttachmentDAO.save(attr);
			                    	}
			                    }
			        	    }
		            	}catch(Exception ex){
		            		LOGGER.error(ex);
		            	}
			    	}
			    	
			    }
		    }
		    
		}
	}
}
